<?php
namespace hema\device\engine;


/**
 * 易联云打印机驱动模块
 * 测试机型号：K4 - K7
 */
class Yilianyun extends Basics
{
    /**
    * 打印订单接口
    * $dev = 设备参数,$content=打印模板
    */
    public function print($dev,$content)
    {
        $content = $this->make_templet($content,$dev['prt_num']);//转换打印模板
        $params = $this->params();
        $params['machine_code'] = $dev['dev_id'];//打印机终端号
        $params['origin_id'] = (string)time();//订单编号
        $params['content'] = $content;//打印内容
        $result = json_decode($this->http_post_json($params,'/print/index'),true);
        sleep(1);//延时1秒
        if($result['error']!=0){
            $this->error = $result['error_description'];
            return false;
        }
        return $result;
    }
    
    /**
    * 授权绑定打印机
    */
    public function add($data)
    {
        $params = $this->params();
        $params['print_name'] = $data['dev_name'];//自定义打印机名称(可填)
        $params['machine_code'] = $data['dev_id'];//打印机终端号
        $params['msign'] = $data['dev_key'];//打印机终端密钥
        $result = json_decode($this->http_post_json($params,'/printer/addprinter'),true);
        if($result['error']!=0){
            $this->error = $result['error_description'];
            return false;
        }
        return $result;
    }
    
    /**
    * 删除授权绑定的打印机
    */
    public function delete($dev_id)
    {
        $params = $this->params();
        $params['machine_code'] = $dev_id;//打印机编号
        $result = json_decode($this->http_post_json($params,'/printer/deleteprinter'),true);
        if($result['error']!=0){
            $this->error = $result['error_description'];
            return false;
        }
        return $result;
    }
    
    /**
    * 获取打印机状态接口 
    */
    public function status($dev_id)
    {
        $params = $this->params();
        $params['machine_code'] = $dev_id;//打印机编号
        $res = json_decode($this->http_post_json($params,'/printer/getprintstatus'),true);
        sleep(1);//延时1秒
        if($res['error']==0){
            $msg = '离线';
            if($res['body']['state']==1){
                $msg = '正常';
            }
            if($res['body']['state']==2){
                $msg = '缺纸';
            }
            return $msg;
        }
        return '未知';
    }

    /**
    * 获取Token
    */
    public function getToken($config)
    {
        $this->config = $config;
        $time = time();
        $params = [
            'client_id' => $this->config['app_key'],
            'timestamp' => $time,
            'sign' => $this->getSign($time),
            'id' => $this->uuid4(),
            'scope' => 'all'
        ];
        $params['grant_type'] = 'client_credentials';
        $result = json_decode($this->http_post_json($params,'/oauth/oauth'),true);
        if($result['error']==0){
            return $result['body']['access_token'];
        }
        return ''; //返回空值
    }

    /**
    * 公共参数
    */
    private function params(){
        $time = time();         //请求时间
        return $params = [
            'client_id' => $this->config['app_key'],
            'access_token' => $this->config['access_token'],
            'timestamp' => $time,
            'sign' => $this->getSign($time),
            'id' => $this->uuid4(),
        ];
    }
    
    /**
    * 生成签名
    */
    private function getSign($timestamp)
    {
        return md5($this->config['app_key'] . $timestamp . $this->config['app_secret']);
    }

    /**
    * 生成uuid4
    */
    private function uuid4(){
        mt_srand((double)microtime() * 10000);
        $charid = strtolower(md5(uniqid(rand(), true)));
        $hyphen = '-';
        $uuidV4 =
            substr($charid, 0, 8) . $hyphen .
            substr($charid, 8, 4) . $hyphen .
            substr($charid, 12, 4) . $hyphen .
            substr($charid, 16, 4) . $hyphen .
            substr($charid, 20, 12);
        return $uuidV4;
    }
    
    
    //发送post请求
    /**
     * PHP发送Json对象数据
     * @return string
     */
    private function http_post_json($data,$url)
    {
        $url = $this->config['api_url'] . $url;
        $data = http_build_query($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Expect:'
        )); // 解决数据包大不能提交
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($ch, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $response;
    }

    /**
     * 制作订单模板
     * $data 订单数据
     * $n 打印份数
     * 58mm的机器,一行打印16个汉字,32个字母;
     */
    private function make_templet($data,$n)
    {
        $content = '<MN>'.$n.'</MN>';
        foreach ($data as $item){
            $row_arr = explode(',',$item);
            $row = $row_arr[0];
            for($m=1;$m<sizeof($row_arr);$m++){
                //放大
                if($row_arr[$m] == '<B>'){
                    $row = "<FS>" . $row . "</FS>";
                }
                //居中
                if($row_arr[$m] == '<C>'){
                    $row = "<center>" . $row . "</center>";
                }
            }
            $content .= $row . "\n";
        }
        $content .= "\n\n";
        return $content;
    }
}
